package com.xinhua.erp.service;

import com.xinhua.erp.pojo.*;
import com.xinhua.erp.repo.PurchaseRepo;
import com.xinhua.erp.utils.IdWorker;
import com.xinhua.erp.utils.OrderNumber;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service

@Transactional
public class PurchaseService {

    @Autowired
    private PurchaseRepo purchaseRepo;

    @Autowired
    private IdWorker idWorker;

    public Result findAll() {

        List<Purchase> list = purchaseRepo.findAll();

        return Result.OK(list);

    }

    public  Result findPurchaseByType(String type, int page, int size){

        Pageable pageable = PageRequest.of(page-1, size);

        Page<Purchase> purchases = purchaseRepo.findAllByType(type, pageable);

        PageResult<Purchase> pageResult =new PageResult<>(purchases.getTotalElements(),purchases.getContent());

        return Result.OK(pageResult);

    }

    public Result findById(long id) {

        return Result.OK(purchaseRepo.getOne(id));
    }

    public Result save(Purchase purchase){
        purchase.setId(idWorker.nextId());

        purchaseRepo.save(purchase);

        return Result.OK();

    }

    public Result update(Purchase purchase) {

        purchaseRepo.save(purchase);

        return Result.OK();
    }

    public Result deleteById(long id) {

        purchaseRepo.deleteById(id);

        return Result.OK();
    }

    public Result updatestatus(Long id) {

        purchaseRepo.updatestatus(id);

        return new Result(true,20000,"审核成功");
    }
}
